package com.atguigu.sparkcore.day04

import org.apache.spark.util.AccumulatorV2

class LongAcc extends AccumulatorV2[Long, Long] {
    // 内部保存和的值的一个变量
    private var _sum: Long = 0L
    
    // 判零
    override def isZero: Boolean = _sum == 0
    
    // 复制: 把当前的累加器复制到奥另外一个地方
    override def copy(): AccumulatorV2[Long, Long] = {
        val acc = new LongAcc
        acc._sum = this._sum
        acc
    }
    
    
    // 重置: 把缓冲区重置为初始值
    override def reset(): Unit = {
        _sum = 0
    }
    
    //  累加:  分区内累加
    override def add(v: Long): Unit = {
        _sum += v
    }
    
    // 分区间的累加  把other合并到this中
    override def merge(other: AccumulatorV2[Long, Long]): Unit = {
        other match {
            case o: LongAcc =>
                this._sum += o._sum
            case _ => throw  new UnsupportedOperationException
        }
    }
    
    // 返回累加后的结果
    override def value: Long = _sum
}
